﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;
using System.Windows.Controls;

namespace ActionModel.Utility
{
	/// <summary>
	/// 以Json格式返回AJAX请求处理结果
	/// </summary>
	public class JsonResult
	{
		bool m_Result = false;
		/// <summary>
		/// 处理结果
		/// </summary>
		public bool Result
		{
			get { return m_Result; }
			set { m_Result = value; }
		}

		string m_ResultMessage;
		/// <summary>
		/// 处理结果详细信息，通常为错误信息
		/// </summary>
		public string ResultMessage
		{
			get { return m_ResultMessage; }
			set { m_ResultMessage = value; }
		}

		object m_ContentObject;
		/// <summary>
		/// 成功完成请求后，携带下一步操作所需要的数据对象
		/// </summary>
		public object ContentObject
		{
			get { return m_ContentObject; }
			set { m_ContentObject = value; }
		}

		public JsonResult() { }

		public JsonResult(bool p_Result, string p_ResultMessage)
		{
			this.m_Result = p_Result;
			this.m_ResultMessage = p_ResultMessage;
		}
		public JsonResult(bool p_Result, string p_ResultMessage, object p_ContentObject)
		{
			this.m_Result = p_Result;
			this.m_ResultMessage = p_ResultMessage;
			this.ContentObject = p_ContentObject;
		}

		public override string ToString()
		{
			return JsonSerializer.ToJSON(this);
		}
		public string toString() { return base.ToString(); }

		/// <summary>
		/// 成功实例
		/// </summary>
		public static JsonResult Success
		{
			get
			{
				return new JsonResult(true, string.Empty);
			}
		}

		/// <summary>
		/// 输出错误信息，并结束响应当前请求
		/// </summary>
		/// <param name="p_ErrorMessage">错误消息</param>
		public static void WriteError(string p_ErrorMessage)
		{
			Write(new JsonResult(false, p_ErrorMessage));
		}
		/// <summary>
		/// 输出成功信息，并结束当前请求的响应
		/// </summary>
		/// <param name="p_ContentObject">客户端继续操作所需内容</param>
		public static void WriteSuccess(object p_ContentObject)
		{
			Write(new JsonResult(true, string.Empty, p_ContentObject));
		}
		/// <summary>
		/// 输出成功信息，并结束当前请求的响应
		/// </summary>
		/// <param name="p_ContentObjects">客户端继续操作所需内容集</param>
		public static void WriteSuccess(params object[] p_ContentObjects)
		{
			Write(new JsonResult(true, string.Empty, p_ContentObjects));
		}

		/// <summary>
		/// 输出成功信息
		/// </summary>
		public static void WriteSuccess()
		{
			WriteSuccess(null);
		}
		/// <summary>
		/// 以Json格式输出实例，并结束当前请求的响应
		/// </summary>
		/// <param name="p_JsonResult"></param>
		public static void Write(JsonResult p_JsonResult)
		{
			HttpResponse response= HttpContext.Current.Response;
			response.Clear();
			response.Cache.SetCacheability(HttpCacheability.NoCache);
			response.ContentType = "application/json";
			response.Write(p_JsonResult);
			response.End();
		}
	}
}
